//
//  PackageHead.swift
//  swifttest1
//
//  Created by kologe on 2024/9/26.
//

import Foundation
import Combine

class PackageHead{
    static let headCount:UINT32 = 12
    var dataCount:UINT32 = 12;//字节数
    var type:UINT32 = UINT32(STRING_MESSAGE)
    var msgnum:UINT32 = 0;
    init(){
        dataCount = 12
        type = UINT32(STRING_MESSAGE)
        msgnum = 0
    }
    
    init(dataCount: UINT32, type: UINT32, msgnum: UINT32) {
        self.dataCount = dataCount
        self.type = type
        self.msgnum = msgnum
    }
    
    func encode()-> Data{
        var data = Data()
        data.append(type.bigEndian.data)
        data.append(dataCount.bigEndian.data)
        data.append(msgnum.bigEndian.data)
        return data
    }
    
    static func decode(data:Data)->PackageHead?{
        if(data.count != headCount){
            return nil
        }
        let type = UINT32(bigEndian: data.subdata(in: 0..<4).withUnsafeBytes { $0.load(as: UINT32.self) })
        let dataCount = UINT32(bigEndian: data.subdata(in: 4..<8).withUnsafeBytes { $0.load(as: UINT32.self) })
        let msgnum = UINT32(bigEndian: data.subdata(in: 8..<12).withUnsafeBytes { $0.load(as: UINT32.self) })
        if(type > RECONNECT){
            error_log("error: type is : \(type) dataCount is :\(dataCount)")
        }
        
        return PackageHead(dataCount: dataCount, type: type, msgnum: msgnum)
    }
    
    static func packageData(msgData:Data,type:UINT32) -> Data{
        //生成包头
        let ph = PackageHead()
        ph.msgnum = 1
        ph.type = type
        ph.dataCount = PackageHead.headCount+UINT32((msgData.count))
        var phData = ph.encode()
        
        
        phData.append(msgData)
        return phData
    }
  
    
   
}

extension UInt32 {
    var data: Data {
        var int = self
        return Data(bytes: &int, count: MemoryLayout<UInt32>.size)
    }
}
